<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Config;
use think\Db;
use think\Url;
use think\Route;
use think\Loader;
use think\Request;
use think\Session;

	/** 
	 * 获取当前登录的管理员ID
	 * @return int
	 */
	function cmf_get_current_admin_id()
	{
	    return Session::get('admin_id');
	}
	/**
	 * 获取文件扩展名
	 * @param string $filename 文件名
	 * @return string 文件扩展名
	 */
	function cmf_get_file_extension($filename)
	{
	    $pathinfo = pathinfo($filename);
	    return strtolower($pathinfo['extension']);
	}

	/**
     * 获取系统配置，通用
     * @param string $key 配置键值,都小写
     * @return array
     */
    function cmf_get_option($key)
    {
        if (!is_string($key) || empty($key)) {
            return [];
        }

        static $cmfGetOption;

        if (empty($cmfGetOption)) {
            $cmfGetOption = [];
        } else {
            if (!empty($cmfGetOption[$key])) {
                return $cmfGetOption[$key];
            }
        }

        $optionValue = cache('cmf_options_' . $key);

        if (empty($optionValue)) {
            $optionValue = Db::table('sz_option')->where('option_name', $key)->value('option_value');
            if (!empty($optionValue)) {
                $optionValue = json_decode($optionValue, true);

                cache('cmf_options_' . $key, $optionValue);
            }
        }

        $cmfGetOption[$key] = $optionValue;

        return $optionValue;
    }

    /**
     * 获取上传配置
     */
    function cmf_get_upload_setting()
    {
        $uploadSetting = cmf_get_option('upload_setting');
        if (empty($uploadSetting) || empty($uploadSetting['file_types'])) {
            $uploadSetting = [
                'file_types' => [
                    'image' => [
                        'upload_max_filesize' => '10240',//单位KB
                        'extensions'          => 'jpg,jpeg,png,gif,bmp4'
                    ],
                    'video' => [
                        'upload_max_filesize' => '10240',
                        'extensions'          => 'mp4,avi,wmv,rm,rmvb,mkv'
                    ],
                    'audio' => [
                        'upload_max_filesize' => '10240',
                        'extensions'          => 'mp3,wma,wav'
                    ],
                    'file'  => [
                        'upload_max_filesize' => '10240',
                        'extensions'          => 'txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar'
                    ]
                ],
                'chunk_size' => 512,//单位KB
                'max_files'  => 20 //最大同时上传文件数
            ];
        }

        if (empty($uploadSetting['upload_max_filesize'])) {
            $uploadMaxFileSizeSetting = [];
            foreach ($uploadSetting['file_types'] as $setting) {
                $extensions = explode(',', trim($setting['extensions']));
                if (!empty($extensions)) {
                    $uploadMaxFileSize = intval($setting['upload_max_filesize']) * 1024;//转化成B
                    foreach ($extensions as $ext) {
                        if (!isset($uploadMaxFileSizeSetting[$ext]) || $uploadMaxFileSize > $uploadMaxFileSizeSetting[$ext] * 1024) {
                            $uploadMaxFileSizeSetting[$ext] = $uploadMaxFileSize;
                        }
                    }
                }
            }

            $uploadSetting['upload_max_filesize'] = $uploadMaxFileSizeSetting;
        }
      
        return $uploadSetting;
    }

    /**
	 * 获取网站根目录
	 * @return string 网站根目录
	 */
	function cmf_get_root()
	{
	    $request = Request::instance();
	    $root    = $request->root();
	    $root    = str_replace('/index.php', '', $root);
	    if (defined('APP_NAMESPACE') && APP_NAMESPACE == 'api') {
	        $root = preg_replace('/\/api$/', '', $root);
	        $root = rtrim($root, '/');
	    }

	    return $root;
	}

    /**
     * 获取图片预览地址
     * @param string $file
     * @param string $style
     * @return mixed
     */
    function getPreviewUrl($file, $style = '')
    {
        return _getWebRoot() . '/upload/' . $file;
    }


    function _getWebRoot()
    {
        return cmf_get_domain() . cmf_get_root();

    }

    /**
     * 返回带协议的域名
     */
    function cmf_get_domain()
    {
        $request = Request::instance();
        return $request->domain();
    }

    /**
     * 获取文件相对路径
     * @param string $assetUrl 文件的URL
     * @return string
     */
    function cmf_asset_relative_url($assetUrl)
    {
        if (strpos($assetUrl, "http") === 0) {
            return $assetUrl;
        } else {
            return str_replace('/upload/', '', $assetUrl);
        }
    }


    /**
    *  将数组转为json
    * @param int $code
    * @param string $msg
    * @param string $data
    * @param string $url
    * @param string $url
    */
    function returnJson($code = 0, $msg='',$data = '', $url = '')
    {
        return json(['code' => $code,'msg' => $msg, 'data' => $data, 'url' => $url]);                                                                                                                                         
        exit;
    }


    /**
    *   base64转为图片
    *   @param string $pic
    */  
    function base64upload($pic)
    {
        $lists = explode("`", $pic);
        $list = [];
        $arr = [];
        foreach ($lists as $key=>$val) {
            if (strstr($val,",")){
                $list[$key] = explode(',',$val);
                
                $arr[$key]['url'] = $list[$key][1];
            }
        }

        $data['pic']['photos'] = [];
        $res = [];
        foreach($arr as $k=>$v){

            //图片名字
            $imageName = "25220_".date("His",time()).rand(1111,9999).'.jpg';
            $up_dir = 'upload/';
            $path = $up_dir.date("Ymd",time());

            if (!is_dir($path)){ //判断目录是否存在 不存在就创建
                mkdir($path,0777,true);
            }

            $imageSrc =  $path."/". $imageName;  //图片名字

            $list = file_put_contents($imageSrc, base64_decode($v['url'])); //返回的是字节数

            if (strstr($imageSrc,".")){
                $res[$k] = explode('.',$imageSrc);
                $imageUrl = '/'.$res[$k][0].'.'.$res[$k][1];
                
            }

            $photoUrl = cmf_asset_relative_url($imageUrl);

            array_push($data['pic']['photos'], ["url" => $photoUrl]);
        }

        return $data;
    }

    /**
    *   获取订单号
    */
    function getOrderCode()
    {
        $ordercode = date('Ymd') . str_pad(mt_rand(1, 99999999), 8, '0', STR_PAD_LEFT);

        return $ordercode;
    }

    


